<template>
    <div>
        <el-input
            placeholder="请输入部门关键字进行搜索"
            v-model="filterText"
            prefix-icon="el-icon-search"
            style="margin-bottom: 15px; width: 500px"
            clearable
        >
        </el-input>

        <el-tree
            :data="departments"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            ref="tree"
            :expand-on-click-node="false"
        >
            <span
                class="custom-tree-node"
                slot-scope="{ data }"
                style="
                    display: flex;
                    justify-content: space-between;
                    width: 100%;
                "
            >
                <span>{{ data.name }}</span>
                <span>
                    <el-button
                        type="primary"
                        size="mini"
                        @click="() => showAddDepartment(data)"
                        class="depBtn"
                    >
                        添加部门
                    </el-button>
                    <el-button
                        type="danger"
                        size="mini"
                        class="depBtn"
                        @click="() => deleteDepartment(data)"
                    >
                        删除部门
                    </el-button>
                </span>
            </span>
        </el-tree>

        <el-dialog
            title="添加部门"
            :visible.sync="dialogVisible"
            width="30%"
            center
        >
            <div>
                <el-row>
                    <el-col :offset="1" :span="6">上级部门：</el-col>
                    <el-col :span="16">
                        <el-input
                            disabled
                            type="text"
                            :placeholder="parentName"
                        ></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :offset="1" :span="6">部门名称：</el-col>
                    <el-col :span="16">
                        <el-input
                            v-model="department.name"
                            placeholder="请输入部门名称..."
                            clearable
                        ></el-input>
                    </el-col>
                </el-row>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button
                    @click="
                        dialogVisible = false;
                        reset();
                    "
                    >取消</el-button
                >
                <el-button type="primary" @click="addDepartment"
                    >确定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 搜索关键字
            filterText: "",
            // 数据
            departments: [],
            // 规则
            defaultProps: {
                children: "children",
                label: "name",
            },
            dialogVisible: false,
            // 上级部门名称
            parentName: "",
            department: {
                name: "",
                parentId: "",
            },
        };
    },
    created() {
        this.initDepartments();
    },
    watch: {
        // 监视输入框的值的变化之后去树形控件中找filter-node-method对应的方法，并把数据传递过去
        filterText(val) {
            this.$refs.tree.filter(val);
        },
    },
    methods: {
        initDepartments() {
            this.getRequest("/system/basic/department/getAllDepartments").then(
                (res) => {
                    if (res) {
                        this.departments = res;
                    }
                }
            );
        },
        filterNode(value, data) {
            // true表示展示整个树形控件
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        // 添加
        showAddDepartment(data) {
            this.parentName = data.name;
            this.department.parentId = data.id;
            this.dialogVisible = true;
        },
        // 删除
        deleteDepartment(data) {
            console.log(data);
            // 判断是否删除的是父部门
            if (data.isParent) {
                return this.$message.error("删除失败，该部门下面还存在子部门");
            }
            this.$confirm(
                "您确定要删除【 " + data.name + " 】这个部门吗?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "只是点错了",
                    type: "warning",
                }
            )
                .then(() => {
                    this.deleteRequest(
                        "/system/basic/department/deleteDepartment/" + data.id
                    ).then((resp) => {
                        if (resp) {
                            this.removeDeptFromDeptTree(
                                null,
                                this.departments,
                                data.id
                            );
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除!",
                    });
                });
        },
        // 手动删除节点树上的部门
        removeDeptFromDeptTree(p, departments, id) {
            for (let i = 0; i < departments.length; i++) {
                let d = departments[i];
                if (d.id === id) {
                    departments.splice(i, 1);
                    if (departments.length == 0) {
                        p.isParent = false;
                    }
                    return;
                } else {
                    this.removeDeptFromDeptTree(d, d.children, id);
                }
            }
        },
        // 添加部门
        addDepartment() {
            this.postRequest(
                "/system/basic/department/addDepartment",
                this.department
            ).then((res) => {
                if (res) {
                    console.log(res);
                    this.addDeptToTree(this.departments, res.obj);
                    this.reset();
                    // this.initDepartments()
                    this.dialogVisible = false;
                }
            });
        },
        // 手动将添加的部门加到对应的子树中
        addDeptToTree(departments, dept) {
            for (let i = 0; i < departments.length; i++) {
                let d = departments[i];
                if (d.id === dept.parentId) {
                    d.children = d.children.concat(dept);
                    if (d.children.length > 0) {
                        d.isParent = true;
                    }
                    return;
                } else {
                    this.addDeptToTree(d.children, dept);
                }
            }
        },
        // 重置添加输入框以及上级部门的禁用输入框
        reset() {
            this.department = {
                name: "",
                parentId: -1,
            };
            // 清空上级部门
            this.parentName = "";
        },
    },
};
</script>

<style scoped>
.depBtn {
    padding: 2px;
}

.el-row {
    padding: 10px;
    display: flex;
    align-items: center;
}
</style>